/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import Model.Artist;
import Model.Artistproductmappings;
import Model.Category;
import Model.Products;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import org.primefaces.event.RateEvent;

/**
 *
 * @author gulben
 */
@ManagedBean(name="detailController")
@RequestScoped
public class DetailController implements Serializable{

    EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
    private List<Artist> productArtists = new ArrayList<Artist>();
    private List<Products> artistProducts = new ArrayList<Products>();
    private Integer productStar;
    private Integer productsCount;
    
    public DetailController() {
    }
    
    public List<Artist> getArtist() {
         EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
         Query query = entityManager.createNamedQuery("Artist.findById");
         query.setParameter("id", Integer.parseInt(getParametresForArtist()));
         List<Artist> artist = (List<Artist>) query.getResultList();
         Iterator<Artist> i = artist.iterator();
         while(i.hasNext()) {
             Artist a = i.next();
             Query query2 = entityManager.createNamedQuery("Artistproductmappings.findArtistId");
             query2.setParameter("artistid", a);
             List<Artistproductmappings> products = (List<Artistproductmappings>) query2.getResultList();
             Iterator<Artistproductmappings> ip = products.iterator();
             while(ip.hasNext()) {
                 Products product = ip.next().getProductid();
                 artistProducts.add(product);
             }
         }
        return artist;
    }
    
    public List<Products> getProduct() {
         EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
         Query query = entityManager.createNamedQuery("Products.findById");
         query.setParameter("id", Integer.parseInt(getParametresForProduct()));
         List<Products> products = (List<Products>) query.getResultList();
         Iterator<Products> i = products.iterator();
         while(i.hasNext()) {
             Products p = i.next();
             productStar = p.getStar();
             Query query2 = entityManager.createNamedQuery("Artistproductmappings.findProductId");
             query2.setParameter("productid", p);
             List<Artistproductmappings> artists = (List<Artistproductmappings>) query2.getResultList();
             Iterator<Artistproductmappings> ia = artists.iterator();
             while(ia.hasNext()) {
                 Artist artist = ia.next().getArtistid();
                 productArtists.add(artist);
             }
         }
        return products;
    }
    
    public List<Products> getProductAboutCategory() {
         EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
         int productId = Integer.parseInt(getParametresForCategory());
         List<Products> products = new ArrayList<Products>() {};
         if(productId != 1 && productId != 2) {
             Query query = entityManager.createNamedQuery("Products.findByCategoryId");
             Category c = new Category();
             c.setId(productId);
             query.setParameter("categoryid", c);
             products = (List<Products>) query.getResultList();
         } else if(productId == 1) {
             products = getBooks();
         } else if(productId == 2) {
             products = getCDs();
         }
         productsCount = products.size();
         return products;
    }
    
    public String getParametresForProduct() {
        Object req = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String productId = ((HttpServletRequest) req).getParameter("productId");
        return productId;
    }
    
    public String getParametresForArtist() {
        Object req = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String artistId = ((HttpServletRequest) req).getParameter("artistId");
        return artistId;
    }
    
    public String getParametresForCategory() {
        Object req = FacesContext.getCurrentInstance().getExternalContext().getRequest();
        String categoryId = ((HttpServletRequest) req).getParameter("categoryId");
        return categoryId;
    }
    
    public String getCategoryName() {
        EntityManager entityManager =  Persistence.createEntityManagerFactory("KitapcdappPU").createEntityManager();
        Query query = entityManager.createNamedQuery("Category.findById");
        query.setParameter("id", Integer.parseInt(getParametresForCategory()));
        List<Category> category = (List<Category>) query.getResultList();
        Iterator<Category> ic = category.iterator();
        String categoryName = null;
        while(ic.hasNext()) {
             categoryName = ic.next().getName();
        }
        return categoryName;
    }
    
    public int getProductCount() {
         int productId = Integer.parseInt(getParametresForCategory());
         List<Products> products = null;
         if(productId != 1 && productId != 2) {
            Query query = entityManager.createNamedQuery("Products.findByCategoryId");
            Category c = new Category();
            c.setId(productId);
            query.setParameter("categoryid", c);
            products = (List<Products>) query.getResultList();
         } else if(productId == 1) {
             products = getBooks();
         } else if(productId == 2) {
             products = getCDs();
         }
         productsCount = products.size();
         return productsCount;
    }
    
    public List<Products> getBooks() {
        List<Integer> bookSubCat = new ArrayList<Integer>() {};
        List<Products> products = new ArrayList<Products>() {};
        Query allParentCategories = entityManager.createNativeQuery("select distinct parentcategoryid from Categorymappings");
        List<Integer> parentCategoryids = (List<Integer>) allParentCategories.getResultList();
        Query allParentCategories2 = entityManager.createNativeQuery("select distinct categoryid from Categorymappings where parentcategoryid=2");
        List<Integer> parentCategoryids2 = (List<Integer>) allParentCategories2.getResultList();
        Query allParentCategories3 = entityManager.createNativeQuery("select distinct parentcategoryid from Categorymappings where parentcategoryid=2");
        List<Integer> parentCategoryids3 = (List<Integer>) allParentCategories3.getResultList();
        parentCategoryids.removeAll(parentCategoryids2);
        parentCategoryids.removeAll(parentCategoryids3);
        for(Integer i : parentCategoryids) {
            if(i != 1) {
                Query categories = entityManager.createNativeQuery("select distinct categoryid from Categorymappings where parentcategoryid=" + i);
                List<Integer> categories2 = (List<Integer>) categories.getResultList();
                Iterator<Integer> ip = categories2.iterator();
                while(ip.hasNext()) {
                    bookSubCat.add(ip.next());
                }
            }
        }
        for (Integer i : bookSubCat) {
            Query query2 = entityManager.createNamedQuery("Products.findByCategoryId");
            Category c = new Category();
            c.setId(i);
            query2.setParameter("categoryid", c);
            List<Products> product = (List<Products>)query2.getResultList();
            Iterator<Products> ip = product.iterator();
            while(ip.hasNext()) {
                products.add(ip.next());
            }
        }
        return products;
    }
    
    public List<Products> getCDs() {
        List<Integer> cdSubCat = new ArrayList<Integer>() {};
        List<Products> products = new ArrayList<Products>() {};
        Query allParentCategories = entityManager.createNativeQuery("select distinct parentcategoryid from Categorymappings");
        List<Integer> parentCategoryids = (List<Integer>) allParentCategories.getResultList();
        Query allParentCategories2 = entityManager.createNativeQuery("select distinct categoryid from Categorymappings where parentcategoryid=1");
        List<Integer> parentCategoryids2 = (List<Integer>) allParentCategories2.getResultList();
        Query allParentCategories3 = entityManager.createNativeQuery("select distinct parentcategoryid from Categorymappings where parentcategoryid=1");
        List<Integer> parentCategoryids3 = (List<Integer>) allParentCategories3.getResultList();
        parentCategoryids.removeAll(parentCategoryids2);
        parentCategoryids.removeAll(parentCategoryids3);
        for(Integer i : parentCategoryids) {
            if(i != 2) {
                Query categories = entityManager.createNativeQuery("select distinct categoryid from Categorymappings where parentcategoryid=" + i);
                List<Integer> categories2 = (List<Integer>) categories.getResultList();
                Iterator<Integer> ip = categories2.iterator();
                while(ip.hasNext()) {
                    cdSubCat.add(ip.next());
                }
            }
        }
        for (Integer i : cdSubCat) {
            Query query2 = entityManager.createNamedQuery("Products.findByCategoryId");
            Category c = new Category();
            c.setId(i);
            query2.setParameter("categoryid", c);
            List<Products> product = (List<Products>)query2.getResultList();
            Iterator<Products> ip = product.iterator();
            while(ip.hasNext()) {
                products.add(ip.next());
            }
        }
        return products;
    }
    
    public void onrate(RateEvent rateEvent) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Rate Event", "You rated:" + ((Integer) rateEvent.getRating()).intValue());
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
     
    public void oncancel() {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Cancel Event", "Rate Reset");
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public List<Artist> getArtists() {
        return productArtists;
    }
    
    public List<Products> getProducts() {
        return artistProducts;
    }
    
    public Integer getProductStar() {
        return productStar;
    }
    
    public void setProductStar(Integer productStar) {
        this.productStar = productStar;
    }
}
